package flp.solvers.random;

import flp.solvers.*;
import flp.Layout;
import flp.exceptions.FlowImpossibleException;
import flp.exceptions.LayoutBuildException;
import flp.problem.ProblemInstance;

/**
 * Algorytm szukajacy najlepszego rozwiazania losujac kolejne Layouty.
 *
 * @author Pipen
 */
public class RandomSolver extends Solver {

    static {
        preferableCostFunction = Layout.CostFunction.DAGSP;
    }
    
    private RandomSettings settings;
    
    public RandomSolver(ProblemInstance toSolve, RandomSettings settings, IOptimizationMonitor optMonitor) {
        super(toSolve, optMonitor);
        this.settings = settings;
    }
    
    
    @Override
    /**
     * Losuje Layouty zadana ilośc razy, zwraca najlepszy.
     */
    public Layout computeSolution() throws LayoutBuildException, FlowImpossibleException
    {   
        try {
            Layout best = Layout.getInstance(toSolve);
            int betterLayoutFoundCounter = 0;

            for (int i = 0; i < settings.getIterations(); i++) {
                if (stoppedFlag){
                    return best;
                }

                Layout nextRandomLayout = Layout.getInstance(toSolve);

                if(best.compareTo(nextRandomLayout, preferableCostFunction) > 0) {
                    best = nextRandomLayout;
                    betterLayoutFoundCounter++;
                }

                Object[] values = { i , best.getCost(preferableCostFunction)};
                optMonitor.markProgress(values);
            }

    //        optMonitor.markProgress("Layout improved: " + betterLayoutFoundCounter + " times\n" +
    //                                "computed Layouts :" + settings.getIterations()    );                   
    //        optMonitor.markProgress("BEST LAYOUT: " + best);
            return best;
        
        } catch (LayoutBuildException ex){
            // metoda zwraca null, ktory handler interpretuje jako rzucenie
            // wyjatku "LayoutBuildException"
            return null;
        }
        
    }

}
